<?php
/**
 * This class is needed to build grids based on a data from DB
 * 
 * Class uses XML files with form description, basic description of relations between 
 * database tables and description of a grid to show data on a webpage.
 * 'FORMS_FILES' constant should be set to define where are these XML files.
 * Class provides methods to build grid, set edit/delete actions.
 * Please, see additional documentation provided with this class.
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Bel Classes
 * @license  New BSD License *
 */ 
class Bel_Grid {	
	/**
	 * Action to edit record
	 *
	 * @var string
	 */
	private $_edit_action;	
	/**
	 * Action to delete record
	 *
	 * @var unknown_type
	 */
	private $_del_action;
	/**
	 * Action to show add form 
	 *
	 * @var string
	 */
	private $_add_action;
	/**
	 * Grid caption
	 *
	 * @var string
	 */
	private $_caption;	
	/**
	 * Call this to get grid array
	 *
	 * @param string $formname - name of a submitted form (also it is a name of xml file with form/tables/grid description )
	 * @param array $result - result of a SQL query 
	 * @return array - data to 'draw' grid
	 */
	public function buildGrid($formname, $result) {
		$grid = array();
		$xml_obj = simplexml_load_file ( FORMS_FILES . $formname . '.xml' );
		$grid_data = $xml_obj->xpath ( '/form/grid' );
		
		$grid['key'] = (string)$grid_data[0]['key'];
		foreach ($grid_data[0]->field as $field){
			$grid ['labels'] [( string ) $field->value] = ( string ) $field->label;
			$i=0;
			foreach($result as $row){
				$grid['rows'][$i][( string ) $field->value] = $row->{( string ) $field->value};
				$i++;
			}
		}

		if(isset($grid['rows'])){
			foreach ($grid['rows'] as $key=>$row){
				$grid['rows'][$key]['key'] = $result[$key]->$grid['key'];			
			}
		}
		
		$grid['add_action'] = $this->_add_action;
		$grid['edit_action'] = $this->_edit_action;
		$grid['delete_action'] = $this->_del_action;		

		return $grid;
	}
	/**
	 * Sets frid caption
	 *
	 * @param string $caption
	 * @return Bel_Grid object
	 */	
	public function setCaption($caption) {
		$this->_caption = $caption;
		return $this;
	}	
	/**
	 * Setter for edit action
	 *
	 * @param string $action - edit action
	 * @return Bel_Grid object
	 */
	public function setEditAction($action) {
		$this->_edit_action = $action;
		return $this;
	}	
	/**
	 * Setter for delete action
	 *
	 * @param string $action - delete action
	 * @return Bel_Grid object
	 */
	public function setDelAction($action) {
		$this->_del_action = $action;
		return $this;
	}	
	/**
	 * Setter for add action
	 *
	 * @param string $action - add action
	 * @return Bel_Grid object
	 */
	public function setAddAction($action) {
		$this->_add_action = $action;
		return $this;
	}
}